import time
import logging
import os

from settings import settings

from starlette.middleware.cors import CORSMiddleware
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles

from routers import api_router


# 创建  FastAPI 实类，供 main.py 调用
def create_application() -> FastAPI:
    # 等待其他组件启动完成
    time.sleep(3)
    application = FastAPI(
        title="FastAPI结构示例",  # 文档标题
        description="使用 FastAPI 实现 Node4j 基础功能. 🚀",  # 文档简介
        version="0.0.1",  # 文档版本号
        # docs_url=None, redoc_url=None,  # 配置离线文档,None 后，http://127.0.0.1:8000/docs 就不能再访问了
    )
    application.include_router(api_router, prefix='/api')  # 后面带API 的就表示接口，路由到 routers 目录下找对应的接口，相当于 Java 的 Controller
    register_middleware(application)  # 支付跨域
    register_static(application)  # 添加HTML静态页面配置
    register_event(application)  # 添加项目事件
    return application


def register_static(app):
    # 如果需要使用静态文件， 可以使用 StaticFiles，将它挂载到应用程序中。
    html_path = os.path.dirname(os.path.abspath(__file__))
    app.mount('/static', StaticFiles(directory=os.path.join(html_path, 'static')))

    @app.get('/')
    async def read_index():
        # 跳转到 static 下面的 index.html 文件
        return FileResponse(os.path.join(html_path, 'static', 'index.html'))

    @app.exception_handler(404)
    async def not_found(request: Request, exc):
        accept = request.headers.get('accept')
        if not accept:
            # 返回JSON 格式
            return JSONResponse(content={'error': "Not found"}, status_code=exc.status_code)
        if exc.status_code == 404 and 'text/html' in accept:
            # 404 跳转到 static 下面的 404.html 页面
            return FileResponse(os.path.join(html_path, 'static', '404.html'))
        else:
            return JSONResponse(content={'error': "Not found"}, status_code=exc.status_code)


# 支持跨域
def register_middleware(application):
    if settings.BACKEND_CORS_ORIGINS:
        application.add_middleware(
            CORSMiddleware,
            allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )


def register_event(app):
    @app.on_event("startup")
    async def startup_event():
        logging.info("App Startup")

    @app.on_event("shutdown")
    async def shutdown_event():
        logging.info("App Shutdown")
